<?php
namespace app\index\controller;

use app\common\model\Activity;
use app\index\model\Wechat\JsApiPay;
use app\index\model\Wechat\WxPayUnifiedOrder;
use app\index\model\Wechat\WxPayApi;
use app\index\model\Wechat\WxPayNotify;
// use app\index\model\Wechat\WxPayOrderQuery;
use app\common\model\User;

class Deal extends Base
{
    public function recharge()
    {
        $amount = (float)$this->request->post('amount');

        if (!$amount) return $this->jsonFail('请选择充值金额');

        // 随机订单号
        $orderNO = time().rand(100000, 99999);

        // 微信支付单位为分
        $amountFen = $amount * 100;
        $amountFormat = number_format($amount, 2);


        $tools = new JsApiPay();
        $input = new WxPayUnifiedOrder();
        $input->SetBody("美育儿：￥ " . $amountFormat);
        $input->SetAttach("美育儿：￥ " . $amountFormat);
        $input->SetOut_trade_no($orderNO);
        $input->SetTotal_fee($amountFen);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("");
        $input->SetNotify_url(config('notify_url'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($this->OauthAccessToken['openid']);
        $order = WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($order);

        echo $jsApiParameters;
        die;
    }

    public function notify()
    {
        $notify = new PayNotifyCallBack();
        $notify->Handle(false);
    }

    public function paySuccess()
    {
        return $this->fetch();
    }

    public function outSuccess()
    {
        return $this->fetch();
    }
}

class PayNotifyCallBack extends WxPayNotify
{
    //查询订单
    public function queryOrder($transaction_id)
    {
        $input = new WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->queryOrder($data["transaction_id"])){
            $msg = "订单查询失败";
            return false;
        }

        // 成功执行方法$data['openid'] $data['total_fee']
        $user = new User();
        $user->changeBalance($data['openid'], $data['total_fee']/100, 0);   // 充值为0
        return true;
    }
}
